<template>
  <el-dialog :title="title" v-model="dialogVisible" width="33%" destroy-on-close>
    <template #default>
      <el-form :rules="rules" :model="roleParams" ref="formRef">
        <el-form-item prop="roleName" label="职位名称">
          <el-input placeholder="请输入职位" v-model="roleParams.roleName" />
        </el-form-item>
      </el-form>
    </template>

    <template #footer>
      <span>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue'
  import { reqAddOrUpdateRole } from '@/api/acl/role'
  import type { RoleData } from '@/api/acl/role/type'
  import type { FormInstance, FormRules } from 'element-plus'
  import { getElMessage } from '@/utils/message'

  const dialogVisible = ref<boolean>(false)
  const formRef = ref<FormInstance>()
  const roleParams = ref<RoleData>({
    id: 0,
    roleName: '',
  })
  const validateRoleName = (_rule: any, value: string, callback: any) => {
    if (value) {
      if (value.trim().length >= 2) {
        callback()
      } else {
        callback(new Error('职位名称至少2位'))
      }
    } else {
      callback(new Error('请输入职位名称'))
    }
  }
  const rules = reactive<FormRules<RoleData>>({
    roleName: [{ required: true, trigger: 'blur', validator: validateRoleName }],
  })
  const title = computed(() => (roleParams.value.id ? '编辑职位' : '添加职位'))

  function open(curRow: RoleData) {
    dialogVisible.value = true
    roleParams.value = JSON.parse(JSON.stringify(curRow))
  }

  const $emits = defineEmits(['reload'])
  async function save() {
    try {
      let isEdit = !!roleParams.value.id
      await formRef.value?.validate(async (valid) => {
        if (!valid) return
        const res: any = await reqAddOrUpdateRole(roleParams.value)
        if (res.code === 200) {
          getElMessage(isEdit ? '编辑职位成功' : '新增职位成功', 'success')
          $emits('reload', { isEdit })
        } else {
          getElMessage(isEdit ? '编辑职位失败' : '新增职位失败', 'error')
        }
      })
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    } finally {
      dialogVisible.value = false
    }
  }

  function cancel() {
    dialogVisible.value = false
  }

  defineExpose({
    open,
    formRef,
  })
</script>

<style lang="scss" scoped></style>
